/*
 * name: jrshare.js
 * version: v0.1.0
 * update: 初始版本
 * date: 2022-05-07
 * author: fyh
 */

define('jrshare', function(require, exports, module){
    var $ = require('jquery');
    var qr = require('qr');

    // 默认配置
    var def = {
        bshare: false, // 是否使用bshare容器
        bdshare: false, // 是否使用bdshare容器
        container: '.jrshare_box',
        qq: '.jrs_qq',
        qzone: '.jrs_qzone',
        weixin: '.jrs_weixin',
        weibo: '.jrs_weibo',
        tieba: '.jrs_tieba',
        douban: '.jrs_douban',
        facebook: '.jrs_facebook',
        linkedin: '.jrs_linkedin',
        twitter: '.jrs_twitter',

        url: '',
        title: '',
        desc: '',
        pic: ''
    };

    // bshare容器
    var bshare = {
        container: '.bshare-custom',
        qq: '.bshare-qqim',
        weixin: '.bshare-weixin',
        weibo: '.bshare-sinaminiblog',
        facebook: '.bshare-facebook',
        linkedin: '.bshare-linkedin',
        twitter: '.bshare-twitter'
    }

    // bdshare容器
    var bdshare = {
        container: '.bdsharebuttonbox',
        qq: '.bds_sqq',
        qzone: '.bds_qzone',
        weixin: '.bds_weixin',
        weibo: '.bds_tsina',
        tieba: '.bds_tieba',
        douban: '.bds_douban'
    }

    // 页面元数据
    var meta = {
        // 页面URL，优先级为twitter:url > og:url > ref="canonical" > location.href
        urls: [
            $('meta[name="twitter:url"]').attr('content'),
            $('meta[property="og:url"]').attr('content'),
            $('link[rel="canonical"]').attr('href'),
            window.location.href
        ],
        // 页面标题，优先级为twitter:title > og:title > title
        titles: [
            $('meta[name="twitter:title"]').attr('content'),
            $('meta[property="og:title"]').attr('content'),
            $('title').text()
        ],
        // 页面描述，优先级为twitter:description > og:description > description
        descs: [
            $('meta[name="twitter:description"]').attr('content'),
            $('meta[property="og:description"]').attr('content'),
            $('meta[name="description"]').attr('content') || $('meta[name="Description"]').attr('content')
        ],
        // 图片，优先级为twitter:image > og:image > 文章第一张 > section第一张
        pics: [
            $('meta[name="twitter:image"]').attr('content'),
            $('meta[property="og:image"]').attr('content'),
            (function(){
                var imgSrc ='';
                var secImg = $('.section').find('img');
                if(secImg.length != 0) {
                    imgSrc =  $('.section').find('img').eq(0).attr('src')
                    if(imgSrc.indexOf('http') === -1) {
                    imgSrc = window.location.origin + imgSrc;
                    }
                }
                var artImg = $('.myart').find('img');
                if(artImg.length != 0) {
                    imgSrc =  $('.myart').find('img').eq(0).attr('src')
                    if(imgSrc.indexOf('http') === -1) {
                    imgSrc = window.location.origin + imgSrc;
                    }
                }
                
                return imgSrc;
            })()
        ]
    };

    // 分享API端点
    var endpoints = {
        qq: 'https://connect.qq.com/widget/shareqq/index.html',
        qzone: 'https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey',
        weibo: 'https://service.weibo.com/share/share.php',
        douban: 'https://www.douban.com/share/service',
        tieba: 'http://tieba.baidu.com/f/commit/share/openShareApi',
        facebook: 'https://www.facebook.com/sharer/sharer.php',
        linkedin: 'https://www.linkedin.com/sharing/share-offsite/',
        twitter: 'https://twitter.com/intent/tweet'
    };

    // 根据优先级获取Meta数据
    function getMeta(key) {
        var result = '';
        var metaArr = meta[key];
        for(var i=0; i<metaArr.length; i++) {
            if(metaArr[i] && metaArr[i].trim()) {
                result = metaArr[i];
                break;
            }
        }
        return result;
    }
    def.url = getMeta('urls'),
    def.title = getMeta('titles'),
    def.desc = getMeta('descs'),
    def.pic = getMeta('pics')

    function initPopupShare(opt, plats) {
        var $container = $(opt.container);
        $.each(plats, function(plat, link) {
            var $plat = $container.find(opt[plat]);
            if($plat.length != 0) {
                $plat.attr('href', 'javascript:void(0);');
                $plat.on('click', function(e){
                    e.preventDefault();
                    window.open(link, 'jrshare-' + plat, 'menubar=no,toolbar=no,location=no,directories=no,status=no,dependent,width=800,height=620,top=100,left=100');
                });
            }
        });
    }

    function initQrShare(opt) {
        var $container = $(opt.container);
        var $weixin = $container.find(opt.weixin);
        if($weixin.length != 0) {
            var $wxbox = $('.jrshare_qrbox.jrshare_wxbox');
            if($wxbox.length === 0) {
                $wxbox = createQrBox('微信', 'jrshare_wxbox');
            }

            $weixin.attr('href', 'javascript:void(0);');
            $weixin.on('click', function(e){
                e.preventDefault();
                $wxbox.fadeIn(200);
            });

            $wxbox.find('.close_btn').on('click', function(){
                $wxbox.fadeOut(200);
            });
        }

        var $qq = $container.find(opt.qq);
        if($qq.length != 0) {
            var $qqbox = $('.jrshare_qrbox.jrshare_qqbox');
            if($qqbox.length === 0) {
                $qqbox = createQrBox('QQ', 'jrshare_qqbox');
            }

            $qq.attr('href', 'javascript:void(0);');
            $qq.on('click', function(e){
                e.preventDefault();
                $qqbox.fadeIn(200);
            });

            $qqbox.find('.close_btn').on('click', function(){
                $qqbox.fadeOut(200);
            });
        }

        function createQrBox(platName, platClass) {
            var $qrbox = $('<div class="jrshare_qrbox ' + platClass + '">\
                                <div class="qrbox_top">\
                                    <span class="qrbox_title">分享到' + platName + '</span>\
                                    <a href="javascript:void(0);" class="close_btn">\
                                        <img src="" alt="关闭"></img>\
                                    </a>\
                                </div>\
                                <div class="qrbox_bott">\
                                    <div class="qrbox_qrcode"></div>\
                                    <div class="qrbox_text"></div>\
                                </div>\
                            </div>').appendTo($(document.body));
            seajs.importStyle('.jrshare_qrbox{display:none; position:fixed; top:50%; left:50%; border:1px solid #d8d8d8; font-size:14px; color:#222; background:#fff; transform: translate(-50%, -50%); z-index:1001; user-select:none;} \
                                .jrshare_qrbox .qrbox_top{position:relative; padding:5px 20px; background:#f2f2f2;}    \
                                .jrshare_qrbox .qrbox_top .close_btn{position:absolute; right:20px; top:10px; width:12px; height:12px;} \
                                .jrshare_qrbox .qrbox_bott{padding:20px;}\
                                ');
            var qrcode = new qr($qrbox.find('.qrbox_qrcode').get(0), {
            text: opt.url,                          // 生成内容
                width: 180,                         // 宽
                height: 180,                        // 高
                colorDark : "#000000",              // 颜色
                colorLight : "#ffffff",             // 背景色
                correctLevel : qr.CorrectLevel.M    // 容错级别 L|M|Q|H
            });
            
            return $qrbox;
        }
    }

    // 导出模块
    // module.exports = function(config) {
    $.jrshare = function(config) {
        // 合并选项
        var opt = $.extend({}, def, config || {});
        if(opt.bshare) {
            opt = $.extend({}, opt, bshare);
        }else if(opt.bdshare) {
            opt = $.extend({}, opt, bdshare);
        }
        
        // 检查容器
        var $container = $(opt.container);
        if($container.length === 0 || $container.attr('data-jrs') === 'loaded') {
            return;
        }

        // 初始化弹窗分享
        initPopupShare(opt, {
            // qq: endpoints.qq + '?url=' + encodeURIComponent(opt.url) 
            //         + '&title=' + encodeURIComponent(opt.title) 
            //         + '&summary=' + encodeURIComponent(opt.desc),
            qzone: endpoints.qzone + '?url=' + encodeURIComponent(opt.url)
                    + '&title=' + encodeURIComponent(opt.title)
                    + '&summary=' + encodeURIComponent(opt.desc)
                    + '&pic=' + encodeURIComponent(opt.pic),

            weibo: endpoints.weibo + '?url=' + encodeURIComponent(opt.url) 
                    + '&title=' + encodeURIComponent((opt.title + '\n' + opt.desc).slice(0, 138 - opt.url.length / 2))
                    + '&pic=' + encodeURIComponent(opt.pic),

            douban: endpoints.douban + '?name=' + encodeURIComponent(opt.title) 
                    + '&href=' + encodeURIComponent(opt.url)
                    + '&image=' + encodeURIComponent(opt.pic)
                    + '&url=' + encodeURIComponent(opt.url) 
                    + '&title=' + encodeURIComponent(opt.title),

            tieba: endpoints.tieba + '?url=' + encodeURIComponent(opt.url)
                    + '&title=' + encodeURIComponent(opt.title)
                    + '&desc=' + encodeURIComponent(opt.desc),
                    //+ '&comment=' + encodeURIComponent(opt.comment),

            facebook: endpoints.facebook + '?u=' + encodeURIComponent(opt.url),
                    // + '&quote=' + encodeURIComponent(opt.title + '\n' + opt.desc),

            linkedin: endpoints.linkedin + '?url=' + encodeURIComponent(opt.url),

            twitter: endpoints.twitter + '?url=' + encodeURIComponent(opt.url) 
                    + '&text=' + encodeURIComponent((opt.title + '\n' + opt.desc).slice(0, 138 - opt.url.length / 2))
                    // + '&via=' + encodeURIComponent(opt.via)
                    // + '&hashtags=' + encodeURIComponent(opt.hashtags)
        });

        // 初始化二维码分享
        initQrShare(opt);

        // 初始化完成，防止重复绑定
        $container.attr('data-jrs', 'loaded');
    }
});